<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2016 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 流年 <liu21st@gmail.com>
// +----------------------------------------------------------------------

// 应用公共文件

/**
 * 获取数据，POST模式
 * @param string $url 指定URL完整路径地址
 * @param string|array $param 请求的数据
 * @param bool $isHttps 是否https协议
 * @param int $timeout 超时时间(秒)
 * @return mixed
 */
function curl_post($url, $param, $isHttps = true, $timeout = 3)
{
    $url = trim($url);
    if (is_array($param)) {
        ksort($param);
        $queryString = http_build_query($param);
    } else {
        $queryString = $param;
    }

    $ch = curl_init();

    if ($isHttps) {
        // 跳过证书检查
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        // 从证书中检查SSL加密算法是否存在
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
    }

    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $queryString);
    curl_setopt($ch, CURLOPT_HEADER, false);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);

    curl_setopt($ch, CURLOPT_HTTPHEADER, ['Expect:']);
    $response = curl_exec($ch);
    curl_close($ch);

    return $response;
}

/**
 * 获取数据，GET模式
 * @param string $url 指定URL完整路径地址
 * @param bool $isHttps 是否https
 * @param int $timeout 请求超时时间
 * @return mixed
 */
function curl_get($url, $isHttps = true, $timeout = 3)
{
    $url = trim($url);
    // 初始化
    $ch = curl_init();

    if ($isHttps) {
        // 跳过证书检查
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        // 从证书中检查SSL加密算法是否存在
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
    }

    // 设置选项，包括URL
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);

    // 执行并获取HTML文档内容
    $output = curl_exec($ch);

    // 释放curl句柄
    curl_close($ch);

    return $output;
}

/**
 * 生成指定长度的随机字符串
 * @param int $length 字符串长度
 * @return string 返回指定长度的随机字符串
 */
function rand_char($length = 32)
{
    $str = '';
    $strPol = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
    $max = strlen($strPol) - 1;
    for ($i = 0; $i < $length; $i++) {
        $str .= $strPol[rand(0, $max)];
    }
    return $str;
}

/**
 * 对用户的密码进行加密
 * @param $password
 * @param $salt //传入随机盐，在输入密码时做认证
 * @return array/password
 */
function password($password, $salt = '')
{
    $pwd = [];
    $pwd['salt'] = $salt ? $salt : rand_char(6);
    $pwd['password'] = md5(md5(trim($password)) . $pwd['salt']);
    return $salt ? $pwd['password'] : $pwd;
}

/**
 * 获取文件后缀
 * @param $fileName
 * @return string
 */
function get_extension($fileName)
{
    return strtolower(pathinfo($fileName, PATHINFO_EXTENSION));
}

/**
 * 获取保存的文件名、路径
 * @param $dir
 * @param $extension
 * @return string
 */
function get_filename($dir, $extension)
{
    return $dir . '/' . date('YmdHis') . mt_rand(10000, 99999) . '.' . $extension;
}

function get_datetime($time)
{
    return $time ? date('Y-m-d H:i:s', $time) : '';
}

/**
 * @param $time
 * @return false|string
 */
function get_date($time)
{
    return $time ? date('Y-m-d', $time) : '';
}

/**
 * 获取当前访问的路由
 * @return string
 */
function get_current_url()
{
    $request = request();
    $module = $request->module();
    $controller = $request->controller();
    $action = $request->action();
    $url = $module . '/' . $controller . '/' . $action;
    // 大写字母转为小写 + 下划线拼接
    return strtolower(preg_replace('/((?<=[a-z])(?=[A-Z]))/', '_', $url));
}

function get_route_url()
{
    $url = \think\facade\Request::baseUrl(false);
    // 判断是否以.html结尾
    if (strrpos($url, '.html') > 0) {
        $url = substr($url, 0, strrpos($url, '.html'));
    } elseif (strrpos($url, '.php') > 0) {
        $url = substr($url, 0, strrpos($url, '.php'));
    }
    if ($url[0] == '/') {
        $url = substr_replace($url, '', 0, 1);
    }
    return $url;
}

/**
 * 截取视频第一帧
 * @param $video
 * @return string
 */
function get_video_img($video)
{
    return $video . '?x-oss-process=video/snapshot,t_1000,f_jpg,w_400,h_400';
}

function download_file($url, $save_dir = './download/', $ext = '')
{
    if (trim($save_dir) == '') {
        $save_dir = './';
    }

    //创建保存目录
    if (!file_exists($save_dir) && !mkdir($save_dir, 0777, true)) {
        return false;
    }

    $ext = $ext ? : substr(strrchr($url, '.'), 0);
    $filename = date('YmdHis') . mt_rand(10000, 99999) . $ext;
    $filePath = $save_dir . $filename;

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // 信任任何证书
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
    $file = curl_exec($ch);
    curl_close($ch);
    $resource = fopen($filePath, 'a');
    fwrite($resource, $file);
    fclose($resource);
    unset($file, $url);

    return ['filename' => $filename, 'filePath' => $filePath];
}

function checkMiniprogram(){
    $agent=isset($_SERVER['HTTP_USER_AGENT']) ? strtolower($_SERVER['HTTP_USER_AGENT']) : ' ';
    if(preg_match('/micromessenger/',$agent)){
        return true;
    }
    return false;
}
